package download

import (
	"common/connect_mgr"
	"euplink/center_rpc"
	"github.com/zeebo/errs"
	"time"
)

func pushNodeToConnectPool(nodes []center_rpc.NodeInfo) {
	devices := make([]connect_mgr.Device, 0)
	for _, n := range nodes {
		devices = append(devices, connect_mgr.Device{
			Id:     n.DevId,
			Port:   n.Port,
			NodeId: n.NodeId,
		})
	}
	connect_mgr.PushAsync(devices)
}

func getLocalPort(devid string, remotePort uint16, timeout time.Duration) (uint16, error) {
	t := time.Now()
	var localport uint16 = 0
	var err error
	for {
		localport, err = connect_mgr.Get(devid, remotePort)
		if err == nil {
			return localport, nil
		}
		time.Sleep(time.Second / 2)
		if time.Now().Sub(t) > timeout {
			if err == connect_mgr.RelayStatus {
				//fmt.Println("返回中继地址")
				return localport, nil
			}
			return 0, errs.New("timeout")
		}
	}
}
